package com.example.camunda.entity;

import lombok.extern.slf4j.Slf4j;
import org.camunda.bpm.engine.impl.cmd.AbstractProcessInstanceModificationCommand;
import org.camunda.bpm.engine.impl.context.Context;
import org.camunda.bpm.engine.impl.db.entitymanager.cache.DbEntityCache;
import org.camunda.bpm.engine.impl.interceptor.CommandContext;
import org.camunda.bpm.engine.impl.persistence.entity.TaskEntity;
import org.camunda.bpm.engine.impl.persistence.entity.TaskManager;

import java.util.List;

@Slf4j
public class ActivityTaskCancellationCmd extends AbstractProcessInstanceModificationCommand {

    protected String deleteReason = "deleted";
    protected String taskId;
    protected final String DELETE_REASON = "deleted";
    public ActivityTaskCancellationCmd(String processInstanceId) {
        super(processInstanceId);
    }

    public ActivityTaskCancellationCmd(String processInstanceId, String taskId , String deleteReason) {
        super(processInstanceId);
        this.taskId = taskId;
        this.deleteReason = deleteReason;
    }

    public Void execute(CommandContext commandContext) {
        final TaskManager taskManager = Context.getCommandContext().getTaskManager();
        final List<TaskEntity> tasks =  taskManager.findTasksByProcessInstanceId(processInstanceId);
        try {
            for (TaskEntity task : tasks) {
                if (task.getId().equals(taskId)) {
                    task.delete(deleteReason, false, false);
                }else{
                    task.delete(DELETE_REASON,false,false);
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }


    protected String describe() {
        return "Cancel activity task '" + taskId + "'";
    }

}
